﻿using System.Windows;
using System.Windows.Input;


namespace AIPASoft.CommonLibrary.WPF.KeyboardHook
{
    public abstract class KeyboardFocusNavigationBase
    {

        public virtual FocusNavigationDirection Default
        {
            get { return FocusNavigationDirection.Next; }
        }

        protected virtual void Register<T>() where T : UIElement
        {
            EventManager.RegisterClassHandler(typeof(T), UIElement.KeyDownEvent,
               new KeyEventHandler(KeyDownEvent));
        }

        public abstract void Register();

        public abstract void UnRegister();

        protected abstract void KeyDownEvent(object sender, KeyEventArgs e);

        protected virtual void MoveToNextUIElement(KeyEventArgs e, FocusNavigationDirection focusNavigation)
        {

            // MoveFocus takes a TraveralReqest as its argument.
            var request = new TraversalRequest(focusNavigation);

            // Gets the element with keyboard focus.
            var elementWithFocus = Keyboard.FocusedElement as UIElement;

            // Change keyboard focus.
            if (elementWithFocus != null)
            {
                if (elementWithFocus.MoveFocus(request))
                {
                    e.Handled = true;
                }
            }

        }

        protected virtual void MoveToNextUIElement(KeyEventArgs e)
        {
            MoveToNextUIElement(e, Default);
        }
    }

}
